//
//  MCActionVc.swift
//  MCBodyBuildingPro
//
//  Created by Renlvshijie on 2023/5/4.
//

import UIKit
import SnapKit
import Toast_Swift
import QMUIKit
import ObjectMapper
import Kingfisher
import MJRefresh


class MCActionVc: MCBaseVc {
        
    let MCLeftTableCellIdentifier = "MCLeftTableCellIdentifier"
    
    let MCRightCollectionIdentifier = "MCRightCollectionIdentifier"
    
    let mcRIghtCollectionResulableIdentifier = "mcRIghtCollectionResulableIdentifier"
    
    var _selectIndex:Int = 0
    
    var leftDataSource:Array = [String]()
    
    var intrumentModelList:Array = [MCRecord]()
    
    private var actionModelList:Array = [MCActionInfoRecord?]()
    
    var count:Int = 1
    
    var position:Int = -1
    
    lazy var leftTableView:UITableView = {
        
        var tableView = UITableView(frame: CGRect.zero, style: .plain)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.separatorStyle = .none
        tableView.backgroundColor = UIColor.qmui_color(withHexString: "#F7F7F9")
        return tableView
        
    }()

    lazy var rightCollectionView:UICollectionView = {
        let collectionViewLayout = UICollectionViewFlowLayout.init()
        var collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: collectionViewLayout)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.backgroundColor = .white// UIColor.qmui_color(withHexString: "#F7F7F9")
        collectionView.showsVerticalScrollIndicator = false
        return collectionView
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let headerNavigationView = UIView.init()
        let navititleLabel = QMUILabel.init()
        navititleLabel.text = "健身动作"
        navititleLabel.font = UIFont(name: "PingFangHK-Semibold", size: 17)
        navititleLabel.textColor = UIColor.qmui_color(withHexString: "#10151C")
        headerNavigationView.addSubview(navititleLabel)
        navititleLabel.snp.makeConstraints { make in
            make.left.equalTo(headerNavigationView.snp.left).offset(16.0.auto())
            make.centerY.equalTo(headerNavigationView.snp.centerY).offset(0.0)
        }
        self.navigationItem.titleView = headerNavigationView
      
        loadWithSubViews()
        
        getLeftData()
         
        self.rightCollectionView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
            self.count = 1
            if self._selectIndex == 1 {
               self.getRightInstrumentData(current: self.count)
            }else{
                if self.position == -1 {
                    self.getRightActionData(current: self.count, position: "")
                }else{
                    self.getRightActionData(current: self.count, position: "\(self.position)")
                }
                
            }
         
        })
        
     //   self.rightCollectionView.mj_header?.beginRefreshing()
        
        self.rightCollectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {
            
            if self._selectIndex == 1 {
                self.getRightInstrumentData(current: self.count)
            }else {
                
                if self.position == -1 {
                    self.getRightActionData(current: self.count, position: "")
                }else {
                    self.getRightActionData(current: self.count, position: "\(self.position)")
                }
                
                
            }
                
           
            
        })
        
       
        self.rightCollectionView.register(UINib(nibName: "MCSelectHeaderReusableView", bundle: Bundle.main), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: mcRIghtCollectionResulableIdentifier)
        
         
    }
    
    func loadWithSubViews() -> Void {
        
        leftTableView.register(MCLeftTableCell.self, forCellReuseIdentifier: MCLeftTableCellIdentifier)
        
        view.addSubview(leftTableView)
        leftTableView.snp.makeConstraints { make in
            make.left.equalTo(view.snp.left).offset(0.0)
            make.top.equalTo(view.snp.top).offset(0.0)
            make.bottom.equalTo(view.snp.bottom).offset(0.0)
            make.width.equalTo(70)
        }
        
        rightCollectionView.register(MCRightCollectionCell.self, forCellWithReuseIdentifier: MCRightCollectionIdentifier)
        view.addSubview(rightCollectionView)
        rightCollectionView.snp.makeConstraints { make in
            make.right.equalTo(view.snp.right).offset(0.0)
            make.top.equalTo(view.snp.top).offset(0.0)
            make.bottom.equalTo(view.snp.bottom).offset(0.0)
            make.width.equalTo(ScreenWidth - 70)
        }
    }
    
    //左边部分
    func getLeftData() -> Void {
        NetWorkRequest(MCActionViewModel.getExercisePosition) { ResponseModel in
            if ResponseModel.code == 200 {
                let bodyList  = Mapper<MCActionbodyModel>().mapArray(JSONString: ResponseModel.dataString)!
                
                self.leftDataSource = (bodyList.map({ actionbodyModel in
                    return actionbodyModel.dictValue ?? ""
                }))
                self.leftDataSource.insert("器械", at: 0)
                self.leftDataSource.insert("全部", at: 0)
                self.leftTableView.reloadData()
                self.leftTableView.selectRow(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: .none)
                self.leftTableView.delegate?.tableView?(self.leftTableView, didSelectRowAt: IndexPath(item: 0, section: 0))
            }else{
                self.view.makeToast("网络失败",position: .center)
            }
        } failureCallback: { ResponseModel in
            self.view.makeToast("网络失败",position: .center)
        }
    }
    
    
    
    
    //器械部分
    func getRightInstrumentData(current:Int) -> Void {
        NetWorkRequest(MCActionViewModel.getInstrumentPageList(current:current)) { ResponseModel in
            self.rightCollectionView.mj_header?.endRefreshing()
            self.rightCollectionView.mj_footer?.endRefreshing()
            
            if ResponseModel.code == 200 {
                if self.count == 1 {
                    self.intrumentModelList.removeAll()
                    let inTrumentModel = MCIntrumentModel(JSONString: ResponseModel.dataString)
                    
                    self.intrumentModelList.append(contentsOf: (inTrumentModel?.records)!)
                    
                    self.rightCollectionView.reloadData()
                }else {
                    let inTrumentModel = MCIntrumentModel(JSONString: ResponseModel.dataString)
                    
                    self.intrumentModelList.append(contentsOf: (inTrumentModel?.records)!)
                    
                    self.rightCollectionView.reloadData()
                }
            }
        } failureCallback: { ResponseModel in
            self.rightCollectionView.mj_header?.endRefreshing()
            self.rightCollectionView.mj_footer?.endRefreshing()
            self.view.makeToast("网络失败",position: .center)
        }
    }
    
    
    //动作部分
    func getRightActionData(current:Int,position:String) -> Void {
        NetWorkRequest(MCActionViewModel.getActionPageListApp(current: current, postition: position)) { ResponseModel in
            let actionModel = MCActionInfoModelList(JSONString: ResponseModel.dataString)
            self.rightCollectionView.mj_header?.endRefreshing()
            self.rightCollectionView.mj_footer?.endRefreshing()
            if current == 1 {
                self.actionModelList.removeAll()
                self.actionModelList.append(contentsOf: actionModel?.records ?? [])
            }else {
                self.count += 1
                self.actionModelList.append(contentsOf: actionModel?.records ?? [])
            }
            self.rightCollectionView.reloadData()
    
        } failureCallback: { ResponseModel in
            self.rightCollectionView.mj_header?.endRefreshing()
            self.rightCollectionView.mj_footer?.endRefreshing()
            self.view.makeToast("网络失败",position: .center)
        }
    }
    
    
}

extension MCActionVc:UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.leftDataSource.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 58
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell:MCLeftTableCell = tableView.dequeueReusableCell(withIdentifier: MCLeftTableCellIdentifier, for: indexPath) as! MCLeftTableCell
        
        let actionBodyModel = self.leftDataSource[indexPath.row];
        
        cell.titleInfLabel.text = actionBodyModel
        
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        _selectIndex = indexPath.row
        
        if indexPath.row == 0 {
            self.count = 1
            self.getRightActionData(current: self.count, position:"")
            
        }else if indexPath.row == 1 {
            self.count = 1
            self.getRightInstrumentData(current: self.count)
            
        }else {
            self.count = 1
            self.getRightActionData(current: self.count, position: "\(indexPath.row)")
            self.position = indexPath.row
        }
        
        self.rightCollectionView.scrollToItem(at: NSIndexPath(item: _selectIndex, section: 0) as IndexPath, at: .top, animated: true)
        
    }
    
    
}

extension MCActionVc:UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
    
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        
        if _selectIndex == 1 {
            return self.intrumentModelList.count
        }else{
            return self.actionModelList.count
        }
       
    }
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if _selectIndex == 1 {
            let fileListModel:MCRecord = self.intrumentModelList[section]
            
            return fileListModel.instrumentList?.count ?? 0
        }else{
            let fileListModel:MCActionInfoRecord? = self.actionModelList[section]
            
            return fileListModel?.actionList?.count ?? 0
        }
        
        
        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 10, left: 12, bottom: 0, right: 12)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 10
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 5
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: (UIScreen.main.bounds.size.width - 70 - 32) / 2 , height: 110.auto())
    }
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:MCRightCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: MCRightCollectionIdentifier, for: indexPath) as! MCRightCollectionCell
        
        if _selectIndex == 1 {
            let intrumentListModelInfo = self.intrumentModelList[indexPath.section]
            
            let listModelInfo = intrumentListModelInfo.instrumentList?[indexPath.row]
            
            
            cell.titleInfoLabel.text = listModelInfo?.zhName
            
            cell.icnImageView.kf.setImage(with:URL(string: listModelInfo?.previewPic ?? ""))
        }else {
            if self.actionModelList.count > indexPath.section {
                let intrumentListModelInfo = self.actionModelList[indexPath.section]
                if intrumentListModelInfo?.actionList?.count ?? 0 > indexPath.row {
                    let listModelInfo = intrumentListModelInfo?.actionList?[indexPath.row]
                    
                    cell.titleInfoLabel.text = listModelInfo?.zhName
                    
                    cell.icnImageView.kf.setImage(with:URL(string: listModelInfo?.previewUrl ?? ""))

                }
            }
            
        }
        
        
        
        return cell
        
    }
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: 200, height: 40)
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        var collectionReusableView:UICollectionReusableView!
        if kind == UICollectionView.elementKindSectionHeader {
            let reusableView:MCSelectHeaderReusableView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: mcRIghtCollectionResulableIdentifier, for: indexPath) as! MCSelectHeaderReusableView
            
            if _selectIndex == 1 {
                let intrumentListModelInfo = self.intrumentModelList[indexPath.section]
                
                reusableView.titleInfoLabel.text = intrumentListModelInfo.firstLetterUpper
                
                collectionReusableView = reusableView
            }else{
                let intrumentListModelInfo = self.actionModelList[indexPath.section]
                
                reusableView.titleInfoLabel.text = intrumentListModelInfo?.firstLetterUpper
                
                collectionReusableView = reusableView
            }
            
            
        }
        
        return collectionReusableView
        
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
         if _selectIndex == 1 {
             
            let intrumentListModelInfo = self.intrumentModelList[indexPath.section]
            let listModelInfo = intrumentListModelInfo.instrumentList?[indexPath.row]
            let actionDetailVc = MCActionMachineryVc.init()
            actionDetailVc.ids = listModelInfo?.id ?? ""
            self.navigationController?.pushViewController(actionDetailVc, animated: true)
             
        }else {
            
            let intrumentListModelInfo = self.actionModelList[indexPath.section]
            let listModelInfo = intrumentListModelInfo?.actionList?[indexPath.row]
            let actionDetailVc = MCActionDetailVc.init()
            actionDetailVc.ids = listModelInfo?.id ?? ""
            self.navigationController?.pushViewController(actionDetailVc, animated: true)
            
        }
        
    }
    
    
}
